﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Threading.Tasks;

namespace CodeCube.SocketServer
{
    public class Listener
    {
        List<Task> TList=new List<Task>();
        Dictionary<int, Task> TDict = new Dictionary<int, Task>();
        Dictionary<int, bool> TSDict = new Dictionary<int, bool>();
        public Listener()
        {

        }
        public async void Start(int port,IReceiveData c)
        {
            if (TDict.ContainsKey(port))
            {
                TSDict[port] = false;
                while (TDict[port].Status == TaskStatus.Running)
                {
                    await Task.Delay(100);
                }
                TSDict[port] = true;
                TDict[port] = new Task(() => ListenPort(port, c));
                TDict[port].Start();
            }
            else
            {
                TSDict.Add(port, true);
                TDict.Add(port, new Task(() => ListenPort(port, c)));
                TDict[port].Start();
            }
        }
        private void ListenPort(int port,IReceiveData c)
        {
            IPAddress localadd = IPAddress.Any;
            TcpListener server = new TcpListener(localadd, port);
            server.Start();
            Byte[] bytes = new byte[4096];
            String data = null;
            TcpClient client = null;
            try
            {
                while (TSDict[port])
                {
                    Console.WriteLine("等待新的连接...");
                    client = server.AcceptTcpClient();
                    Console.WriteLine("连接成功！");
                    data = null;
                    NetworkStream nstream = client.GetStream();
                    int offset;
                    while ((offset = nstream.Read(bytes, 0, bytes.Length)) != 0)
                    {
                        c.ReceiveDataAsync(bytes,offset);
                        data = System.Text.Encoding.UTF8.GetString(bytes, 0, offset);
                        Console.WriteLine("收到了：" + data);
                        byte[] msg = System.Text.Encoding.UTF8.GetBytes(data);
                        nstream.Write(msg, 0, msg.Length);
                        Console.WriteLine("发送了:{0}", data);
                    }
                }
            }
            catch (Exception ex)
            {
                client.Close();
                Console.WriteLine(ex.Message);
            }
            Console.WriteLine("服务器已停止.");
            Console.ReadLine();
        }
    }
}
